<template>
    <div class="user-edit-container">
        <input
            type="file"
            hidden
            ref="file"
            accept="image/*"
            @change="fileChange"
        />
        <van-cell
            title="头像"
            is-link
            center
            @click="$refs.file.click()"
        >
            <van-image
                class="user-image"
                round
                fit='cover'
                :src="userProfile.photo"
            />
        </van-cell>
        <van-cell
            title="昵称"
            is-link
            :value="userProfile.name"
            @click="isEditName = true"
        />
        <van-cell
            title="性别"
            is-link
            :value="userProfile.sex"
            @click="isEditSex = true"
        />
        <van-cell
            title="生日"
            is-link
            :value="userProfile.birthday"
            @click="isEditBirthday = true"
        />
        <!-- 编辑昵称的弹出层 -->
        <van-popup
            class="edit-name"
            v-model="isEditName"
            position="bottom"
            get-container="body"
            safe-area-inset-bottom
        >
            <van-nav-bar
                left-text="取消"
                title="昵称"
                right-text="完成"
                safe-area-inset-top
                @click-left="onCancle('name', 'Name')"
                @click-right="nameConfirm"
            />
            <van-field
                v-model="name"
                type="textarea"
                maxlength="7"
                placeholder="输入昵称"
                :error-message="nameError ? errorMsg : ''"
                show-word-limit
            />
        </van-popup>
        <!-- 编辑性别的选择器 -->
        <van-popup
            class="edit-sex-popup"
            v-model="isEditSex"
            position="bottom"
            get-container="body"
            safe-area-inset-bottom
        >
            <van-picker
                class="edit-sex-picker"
                title="性别"
                show-toolbar
                :default-index="userProfile.gender"
                :columns="sexColumns"
                @confirm="sexConfirm"
                @cancel="onCancle('sex', 'Sex')"
            />
        </van-popup>
        <!-- 编辑生日的时间选择器 -->
        <van-popup
            class="edit-birthday-popup"
            v-model="isEditBirthday"
            position="bottom"
            get-container="body"
            safe-area-inset-bottom
        >
            <van-datetime-picker
                class="edit-datetime-picker"
                v-model="birthday"
                type="date"
                title="选择年月日"
                @confirm="birthdayConfirm"
                @cancel="onCancle('birthday', 'Birthday')"
            />
        </van-popup>
        <!-- 修改头像的弹出层 -->
        <van-popup
            class="edit-photo-popup"
            v-model="isEditPhoto"
            position="bottom"
            get-container="body"
            safe-area-inset-bottom
        >
            <EditPhoto
                :file="file"
                @close="isEditPhoto = false"
                @update-img="userProfile.photo = $event"
            />
        </van-popup>
    </div>
</template>

<script>
import dayjs from 'dayjs';
import * as Api from 'api/common';
import EditPhoto from './__editPhoto__';

export default {
    name: 'userEdit',
    components: {
        EditPhoto
    },
    props: {
    },
    // 监控data中的数据变化
    watch: {},
    // 定义属性
    data () {
        return {
            target: null,
            userProfile: {},
            isEditName: false,
            isEditSex: false,
            isEditBirthday: false,
            isEditPhoto: false,
            name: '',
            sex: '',
            nameError: false,
            errorMsg: null,
            sexColumns: ['男', '女'],
            birthday: '',
            file: null
        };
    },
    // 计算属性，会监听依赖属性值随之变化
    computed: {
    },
    // 方法集合
    methods: {
        async getUserInfo () {
            const params = {
                target: +this.target
            };
            const res = await Api.reqDev('/v1_0/user/profile', 'get', { params });
            if (res.message === 'OK') {
                this.userProfile = res.data;
                this.$set(this.userProfile, 'sex', this.userProfile.gender ? '女' : '男');
                this.name = res.data.name;
                let timeList = this.userProfile.birthday.split('-');
                this.birthday = new Date(timeList[0], timeList[1] - 1, timeList[2]);
            }
        },
        onCancle (type, typeUp) {
            this['isEdit' + typeUp] = false;
            this[type] = '';
        },
        async nameConfirm () {
            if (!this.name) {
                this.nameError = true;
                this.errorMsg = '新昵称不能为空';
                return;
            }
            if (this.name === this.userProfile.name) {
                this.nameError = true;
                this.errorMsg = '新昵称和原昵称一样';
                return;
            }
            this.nameError = false;
            this.errorMsg = null;
            const newData = await this.sendMessage({ name: this.name });
            this.userProfile.name = newData.name;
            this.isEditName = false;
        },
        async sexConfirm (sex, index) {
            if (sex !== this.userProfile.sex) {
                await this.sendMessage({ gender: index });
                this.userProfile.sex = sex;
                this.userProfile.gender = index;
            }
            this.isEditSex = false;
        },
        async birthdayConfirm (time) {
            const timeFormat = dayjs(time).format('YYYY-MM-DD');
            if (timeFormat !== this.userProfile.birthday) {
                await this.sendMessage({ birthday: timeFormat });
                this.userProfile.birthday = timeFormat;
            }
            this.isEditBirthday = false;
        },
        async sendMessage (editData) {
            const { name, gender, birthday } = editData;
            const data = {
                name,
                gender,
                birthday
            };
            const res = await Api.reqDev('/v1_0/user/profile', 'patch', { data });
            if (res.message === 'OK') {
                this.$toast.success('编辑成功');
                return res.data;
            }
        },
        fileChange () {
            // 获取图片文件对象
            this.file = this.$refs.file.files[0];
            // 显示弹出层
            this.isEditPhoto = true;
            // 手动清空 input 的 value 属性，使得当用户选择同一图片时也能触发预览操作
            this.$refs.file.value = '';
        }
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created () {
        const { id } = this.$route.query;
        if (!id) {
            this.$toast.fail('参数错误');
            this.$router.replace('/user');
            return;
        }
        this.target = id;
        this.getUserInfo();
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted () {
    }
};
</script>

<style lang='less' scoped>
.user-edit-container {
    .user-image {
        width: 40px;
        height: 40px;
    }
}
.edit-name {
    height: 100%;
    background-color: rgb(252,249,249);
    .van-field {
        margin: 10px;
        width: unset;
    }
}
.edit-sex-popup, .edit-birthday-popup, .edit-photo-popup {
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
}
.edit-photo-popup {
    display: flex;
    align-items: center;
    justify-content: center;
}
.edit-datetime-picker, .edit-sex-picker {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
}
</style>
